package com.myebills.ebpsfrontend.cust.maxis;

import com.myebills.ebpsfrontend.cust.controller.*;
import com.myebills.ebpsfrontend.cust.utils.*;
import com.checkfree.isolutions.customer.persist.Account;
import com.checkfree.isolutions.customer.persist.User;
import com.checkfree.isolutions.customer.persist.Merchant;
import com.checkfree.isolutions.customer.persist.MerchantHomeImpl;
import com.checkfree.isolutions.admin.ObjectId;
import com.checkfree.isolutions.statement.StatementSection;
import com.checkfree.isolutions.property.Properties;
import com.checkfree.isolutions.property.PropertiesConfig;
import com.checkfree.isolutions.statement.persist.Statement;
import java.text.*;
import java.util.*;
import java.text.SimpleDateFormat;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.io.*;


import java.io.IOException;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.*;

import javax.servlet.http.HttpServlet;

public class DownloadBillCSVServlet_v1r00 extends EbppxTransactionServlet {

    /**
     * Load statement and account objects into request.
     * Expecting "statementId" and "accountId" in request.
     */
    public void doTransaction(HttpServletRequest req, HttpServletResponse res)
    throws ServletException {
        try {
            final HttpSession session = req.getSession(false);
            if (null == session) {
                throw new ServletException("Session must be already established");
            }

            Blob zip = null;
		    Connection conn = null;
		    java.sql.Statement stmt = null;
		    ResultSet rs = null;

            final EbppxEcsUser ecsUser = (EbppxEcsUser) session.getAttribute(EbppxConstants.ECS_USER);
            Merchant cfiMerchant = MerchantHomeImpl.singleton().findByName(ecsUser.getMerchantName());
            User cfiUser = getUserHome().findByLogonIdAndMerchant(ecsUser.getUserId(),cfiMerchant);

    		final String randomKey = (String) session.getAttribute(EbppxConstants.RANDOM_KEY);

            final EbppxUrlManager urlManager = getUrlManager(req);
            final String tempInstanceId = urlManager.getSecureParameter("instanceId");
            final String instanceId = EncryptionHelper.decrypt(tempInstanceId,randomKey);

            final String sOidStatement = urlManager.getSecureParameter(EbppxConstants.STATEMENT_ID);
            if (sOidStatement.length() == 0) {
                throw new ServletException("Missing statement identifier");
            }

            final String sOidAccount   = urlManager.getSecureParameter(EbppxConstants.ACCOUNT_ID);
            if (sOidAccount.length() == 0) {
                throw new ServletException("Missing account identifier");
            }

            final Account acct = getAccountHome().findById(new ObjectId(EncryptionHelper.decrypt(sOidAccount,randomKey)));
            final com.checkfree.isolutions.statement.persist.Statement statement = getStatementHome().findById(new ObjectId(EncryptionHelper.decrypt(sOidStatement,randomKey)));

            final char cfiUserRole = cfiUser.getRole();

			String downloadCSVUrl = EbppxCusConstants.DLOAD_CSV;
			java.util.Date dtStmtDate = statement.getDate();
			String stmtDate = DateUtil.formatDate(dtStmtDate,"dd/mm/yyyy");

			com.checkfree.isolutions.admin.ObjectId objectId = new com.checkfree.isolutions.admin.ObjectId(com.checkfree.isolutions.streaming.IClassId.STATEMENT, (int)statement.getInstanceId());
			String statementId = objectId.toString(true);

			String parameter = "?instanceId=" + EncryptionHelper.encodeURL(EncryptionHelper.encrypt(instanceId,randomKey)) +"&statementId=" + EncryptionHelper.encodeURL(EncryptionHelper.encrypt(statementId,randomKey)) + "&accountId=" + EncryptionHelper.encodeURL(sOidAccount);
			downloadCSVUrl = downloadCSVUrl + EbppxUtil.getVersion(downloadCSVUrl,stmtDate) + parameter;

            final String update = req.getParameter("update");
            String acctNo = acct.getExternalKey();

            if(update!=null && update.equals("yes")){
				cfiUser.setProperty("CorporateBillTNC","yes");
			}

            String corpBillTNC = cfiUser.getProperty("CorporateBillTNC");
            boolean boolCorpCust = false;

            if(AcctDetails.getCorpCust(acctNo).equals("1") || AcctDetails.getCorpCust(acctNo).equals("2") || AcctDetails.getCorpCust(acctNo).equals("3") || AcctDetails.getCorpCust(acctNo).equals("4")){
				boolCorpCust = true;
			}

			if(boolCorpCust &&!corpBillTNC.equals("")){
	      		String filename = instanceId+".zip";
				ServletOutputStream out = res.getOutputStream();
      			res.setContentType("application/zip");
				res.setHeader("Content-Disposition","inline; filename=" + filename);

            	String query = "SELECT zipBLOB " +
            	    "FROM   statementext " +
            	    "WHERE  instanceID = " + instanceId;

            	//ServletOutputStream out = res.getOutputStream();

            	try {
					conn = EbppxCusDBUtil.getDbConnection();
				} catch (Exception e) {
					 redirectToMappedUrl(
					                req,
					                res,
					                EbppxConstants.URL_LOGON_FAILURE_PARAM,
            	    EbppxConstants.MESSAGE_0 + "=" + java.net.URLEncoder.encode("Connection not found"));
				}

				try {
            		// log activity start
            		String dateString = DateUtil.formatDate(new java.util.Date());
            		final java.util.Date dtVal = statement.getDate();
            		String stmtDateString = DateUtil.formatDate(dtVal);

            		EbppxCusDBUtil.logUserActivity(EbppxConstants.DOWNLOAD_CSV, acct.getExternalKey(),ecsUser.getUserId(),EbppxConstants.CUSTOMER, EbppxConstants.STATUS_DOWNLOADED, dateString,stmtDateString,"","","","");

					stmt = conn.createStatement();
					rs = stmt.executeQuery(query);

      				if (rs.next()) {
        				zip = rs.getBlob(1);
      				}

      				InputStream in = zip.getBinaryStream();
      				int length = (int) zip.length();

      				int bufferSize = 1024;
      				byte[] buffer = new byte[bufferSize];

      				while ((length = in.read(buffer)) != -1) {
      				  System.out.println("writing " + length + " bytes");
      				  out.write(buffer, 0, length);
      				}

      					in.close();
      					out.flush();

    			} catch (SQLException e) {
					 redirectToMappedUrl(
					                req,
					                res,
					                EbppxConstants.URL_LOGON_FAILURE_PARAM,
            	    EbppxConstants.MESSAGE_0 + "=" + java.net.URLEncoder.encode(e.getMessage()));
				}finally {
					try {
						rs.close();
        				stmt.close();
        				conn.close();
      				} catch (SQLException e) {
						e.printStackTrace();
					}
      			}
			}else{ // end if tnc!=""
	            req.setAttribute("downloadUrl", downloadCSVUrl);
				forwardToMappedUrl(req, res, EbppxConstants.URL_JSP_PARAM);
			}
        } catch (ServletException e) {
            // Just re-throw these
            throw e;
        } catch (Throwable t) {
            throw new ServletException(t.toString(), t);
        }
	}
}

